<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <MenuTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="目录名称" prop="catalogName">
            <el-input
              v-model="queryParams.catalogName"
              placeholder="请输入目录名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-table v-loading="loading" :data="list">
          <el-table-column
            label="资源名称"
            align="center"
            prop="catalogName"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="数据单位" align="center" prop="deptName" width="180" />
          <el-table-column label="查看量" align="center" width="180">
            <template #default="scope">
              {{ scope.row.pageView ?? 0 }}
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updateTime" width="180" />
          <!-- 新增设置按钮列 -->
          <el-table-column label="操作" align="center" width="120">
            <template #default="scope">
              <el-button link type="primary" @click="openSettingsDialog(scope.row)">
                <Icon icon="ep:setting" />设置
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 设置弹窗 - 使用base/info页面的内容 -->
  <el-dialog
    v-model="settingsDialogVisible"
    title="接口设置"
    width="90%"
    :before-close="handleDialogClose"
  >
    <div class="settings-content">
      <!-- 搜索工作栏 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="dialogQueryParams"
          ref="dialogQueryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="接口名称" prop="interfaceName">
            <el-input
              v-model="dialogQueryParams.interfaceName"
              placeholder="请输入接口名称"
              clearable
              @keyup.enter="handleDialogQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="接口方法" prop="interfaceMethod">
            <el-select
              v-model="dialogQueryParams.interfaceMethod"
              placeholder="请选择接口类型"
              clearable
              class="!w-240px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.JIEKOU_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="接口编码" prop="interfaceCode">
            <el-input
              v-model="dialogQueryParams.interfaceCode"
              placeholder="请输入接口编码"
              clearable
              @keyup.enter="handleDialogQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleDialogQuery"
              ><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button
            >
            <el-button @click="resetDialogQuery"
              ><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button
            >
            <!-- 新增更换接口设置按钮 -->
            <el-button @click="handleChangeInterface" type="warning"
              ><Icon icon="ep:refresh-left" class="mr-5px" /> 更换接口设置</el-button
            >
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table
          row-key="id"
          v-loading="dialogLoading"
          :data="dialogList"
          :show-overflow-tooltip="true"
          @current-change="handleCurrentChange"
          highlight-current-row
          ref="dialogTableRef"
        >
          <!-- 使用单选列 -->
          <el-table-column label="序号" align="center" width="80">
            <template #default="scope">
              {{ (dialogQueryParams.pageNo - 1) * dialogQueryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column label="接口名称" align="center" prop="interfaceName" width="180px" />
          <el-table-column label="服务地址" align="center" prop="serviceUrl" />
          <el-table-column label="接口路径" align="center" prop="interfacePath" />
          <el-table-column label="接口类型" align="center" prop="interfaceType" />
          <el-table-column label="接口方法" align="center" prop="interfaceMethod">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.JIEKOU_TYPE" :value="scope.row.interfaceMethod" />
            </template>
          </el-table-column>
          <el-table-column label="接口编码" align="center" prop="interfaceCode" />
          <el-table-column
            label="Content-Type类型"
            align="center"
            prop="contentType"
            width="200px"
          />
          <el-table-column label="请求示例" align="center" width="120">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="showJsonDialog('请求示例', scope.row.requestExample)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="响应示例" align="center" width="120">
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="showJsonDialog('响应示例', scope.row.responseExample)"
              >
                查看
              </el-button>
            </template>
          </el-table-column>
          <el-table-column
            label="申请次数"
            align="center"
            prop="numberOfApplications"
            width="200px"
          />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />
        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="dialogTotal"
          v-model:page="dialogQueryParams.pageNo"
          v-model:limit="dialogQueryParams.pageSize"
          @pagination="getDialogList"
        />
      </ContentWrap>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit"> 提交选中接口 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- JSON查看弹窗 -->
  <el-dialog v-model="jsonDialogVisible" :title="jsonDialogTitle" width="800px">
    <el-input v-model="jsonContent" type="textarea" :rows="20" readonly placeholder="暂无数据" />
    <template #footer>
      <el-button @click="jsonDialogVisible = false">关闭</el-button>
      <el-button type="primary" @click="copyJson">复制</el-button>
    </template>
  </el-dialog>

  <!-- 表单弹窗：添加/修改 - 直接整合到页面中 -->
  <el-dialog v-model="formDialogVisible" :title="formDialogTitle" width="90%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="服务地址" prop="serviceUrl">
        <el-input
          v-model="formData.serviceUrl"
          placeholder="请输入服务地址"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="接口路径" prop="interfacePath">
        <el-input
          v-model="formData.interfacePath"
          placeholder="请输入接口路径"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="接口类型" prop="interfaceType">
        <el-input v-model="formData.interfaceType" placeholder="请输入接口类型" />
      </el-form-item>
      <el-form-item label="接口方法" prop="interfaceMethod">
        <el-select
          v-model="formData.interfaceMethod"
          placeholder="请选择接口方法"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in interfaceMethodOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="接口名称" prop="interfaceName">
        <el-input
          v-model="formData.interfaceName"
          placeholder="请输入接口名称"
          maxlength="100"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="接口编码" prop="interfaceCode">
        <el-input v-model="formData.interfaceCode" placeholder="请输入接口编码" />
      </el-form-item>
      <el-form-item label="Content-Type类型" prop="contentType">
        <el-input v-model="formData.contentType" placeholder="请输入Content-Type类型" />
      </el-form-item>
      <el-form-item label="请求示例" prop="requestExample">
        <el-input
          v-model="formData.requestExample"
          type="textarea"
          :rows="6"
          placeholder="请输入请求示例（JSON格式）"
          @blur="validateJson('requestExample')"
        />
        <div class="flex justify-end mt-8px">
          <el-button link type="primary" @click="formatJson('requestExample')"> 格式化 </el-button>
          <el-button link type="primary" @click="clearJson('requestExample')"> 清空 </el-button>
        </div>
      </el-form-item>
      <el-form-item label="响应示例" prop="responseExample">
        <el-input
          v-model="formData.responseExample"
          type="textarea"
          :rows="6"
          placeholder="请输入响应示例（JSON格式）"
          @blur="validateJson('responseExample')"
        />
        <div class="flex justify-end mt-8px">
          <el-button link type="primary" @click="formatJson('responseExample')"> 格式化 </el-button>
          <el-button link type="primary" @click="clearJson('responseExample')"> 清空 </el-button>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="formDialogVisible = false">取 消</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import * as portApi from '@/api/business/port'
import { InfoApi } from '@/api/base/info'
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import MenuTree from './MenuTree.vue'
import { nextTick } from 'vue'

/** 业务门户 列表 */
defineOptions({ name: 'BusinessPort' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 主页面数据
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  catalogName: undefined,
  status: undefined,
  menuId: undefined
})
const queryFormRef = ref() // 搜索的表单

// 弹窗相关数据
const settingsDialogVisible = ref(false)
const dialogLoading = ref(false)
const dialogTotal = ref(0)
const dialogList = ref([])
const selectedRow = ref(null) // 选中的行数据
const dialogQueryFormRef = ref()
const dialogTableRef = ref() // 弹窗表格的引用
const infoId = ref<string>() // 用于回显的infoId
const originalInfoId = ref<string>() // 保存原始infoId，用于恢复状态

const dialogQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  serviceUrl: undefined,
  interfacePath: undefined,
  interfaceType: undefined,
  interfaceMethod: undefined,
  interfaceCode: undefined,
  contentType: undefined,
  createTime: [],
  remark: undefined,
  interfaceName: undefined,
  id: undefined // 新增：用于传递infoId查询参数
})

// JSON查看相关
const jsonDialogVisible = ref(false)
const jsonDialogTitle = ref('')
const jsonContent = ref('')

// 表单相关数据 (原InfoForm组件的内容)
const formDialogVisible = ref(false)
const formDialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref({
  id: undefined,
  serviceUrl: undefined,
  interfacePath: undefined,
  interfaceType: undefined,
  interfaceMethod: undefined,
  interfaceName: undefined,
  interfaceCode: undefined,
  contentType: undefined,
  requestExample: undefined,
  responseExample: undefined,
  remark: undefined
})

// 表单规则
const formRules = reactive({
  serviceUrl: [{ required: true, message: '服务地址不能为空', trigger: 'blur' }],
  interfacePath: [{ required: true, message: '接口路径不能为空', trigger: 'blur' }],
  interfaceType: [{ required: true, message: '接口类型不能为空', trigger: 'change' }],
  interfaceMethod: [{ required: true, message: '接口方法不能为空', trigger: 'change' }],
  interfaceName: [{ required: true, message: '接口名称不能为空', trigger: 'blur' }],
  interfaceCode: [{ required: true, message: '接口编码不能为空', trigger: 'blur' }],
  requestExample: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value && value.trim()) {
          try {
            JSON.parse(value)
            callback()
          } catch (e) {
            callback(new Error('请求示例必须是有效的JSON格式'))
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  responseExample: [
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value && value.trim()) {
          try {
            JSON.parse(value)
            callback()
          } catch (e) {
            callback(new Error('响应示例必须是有效的JSON格式'))
          }
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

const formRef = ref()

// 接口方法选项（处理类型转换）
const interfaceMethodOptions = computed(() => {
  const intOptions = getIntDictOptions(DICT_TYPE.JIEKOU_TYPE)
  return intOptions.map((option) => ({
    ...option,
    value: String(option.value)
  }))
})

/** JSON格式化 (表单中的JSON处理) */
const formatJson = (field: 'requestExample' | 'responseExample') => {
  if (!formData.value[field]) return

  try {
    const jsonObj = JSON.parse(formData.value[field]!)
    formData.value[field] = JSON.stringify(jsonObj, null, 2)
    message.success('格式化成功')
  } catch (e) {
    message.error('JSON格式错误，无法格式化')
  }
}

/** JSON验证 */
const validateJson = (field: 'requestExample' | 'responseExample') => {
  if (!formData.value[field] || !formData.value[field]!.trim()) return

  try {
    JSON.parse(formData.value[field]!)
  } catch (e) {
    message.error(`${field === 'requestExample' ? '请求示例' : '响应示例'}JSON格式错误`)
  }
}

/** 清空JSON */
const clearJson = (field: 'requestExample' | 'responseExample') => {
  formData.value[field] = undefined
}

/** 打开表单弹窗 */
const openForm = async (type: string, id?: number) => {
  formDialogVisible.value = true
  formDialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  if (id) {
    formLoading.value = true
    try {
      const info = await InfoApi.getInfo(id)
      formData.value = {
        ...info,
        interfaceMethod:
          info.interfaceMethod !== null && info.interfaceMethod !== undefined
            ? String(info.interfaceMethod)
            : undefined
      }
    } finally {
      formLoading.value = false
    }
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    serviceUrl: undefined,
    interfacePath: undefined,
    interfaceType: undefined,
    interfaceMethod: undefined,
    interfaceName: undefined,
    interfaceCode: undefined,
    contentType: undefined,
    requestExample: undefined,
    responseExample: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}

/** 提交表单 */
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      interfaceMethod: formData.value.interfaceMethod
        ? Number(formData.value.interfaceMethod)
        : undefined
    }

    if (formType.value === 'create') {
      await InfoApi.createInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await InfoApi.updateInfo(data)
      message.success(t('common.updateSuccess'))
    }
    formDialogVisible.value = false
    // 刷新列表数据
    await getList()
  } finally {
    formLoading.value = false
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await portApi.getResourceDirectoryPage(queryParams)
    list.value = data.list.map((item) => ({
      ...item,
      status: item.status ?? '1'
    }))
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 弹窗查询列表 */
const getDialogList = async () => {
  dialogLoading.value = true
  try {
    // 设置查询参数：如果有infoId就加上，没有就不加
    const queryParams = { ...dialogQueryParams }
    if (infoId.value) {
      queryParams.id = parseInt(infoId.value)
    } else {
      queryParams.id = undefined
    }

    const data = await InfoApi.getInfoPage(queryParams)
    dialogList.value = data.list
    dialogTotal.value = data.total

    // 数据加载完成后，处理选中状态
    nextTick(() => {
      if (infoId.value && dialogList.value.length > 0 && dialogTableRef.value) {
        // 查找匹配infoId的行
        const matchedRow = dialogList.value.find((row) => row.id === parseInt(infoId.value!))
        if (matchedRow) {
          // 找到匹配行，设置选中
          dialogTableRef.value.setCurrentRow(matchedRow)
          selectedRow.value = matchedRow
        } else {
          // infoId存在但找不到匹配行，清除选中
          dialogTableRef.value.setCurrentRow()
          selectedRow.value = null
        }
      } else if (infoId.value === null || infoId.value === undefined) {
        // infoId为null，清除选中状态
        if (dialogTableRef.value) {
          dialogTableRef.value.setCurrentRow()
        }
        selectedRow.value = null
      }
    })
  } finally {
    dialogLoading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 弹窗搜索按钮操作 */
const handleDialogQuery = () => {
  dialogQueryParams.pageNo = 1
  getDialogList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 弹窗重置按钮操作 */
const resetDialogQuery = () => {
  dialogQueryFormRef.value?.resetFields()
  handleDialogQuery()
}

/** 处理部门被点击 */
const handleDeptNodeClick = async (row: any) => {
  if (row === undefined) {
    queryParams.menuId = undefined
    await getList()
  } else {
    queryParams.menuId = row.id
    await getList()
  }
}

const catalogIdValue = ref()
const infoIdValue = ref()

const setInterface = async (catalogId: number, infoId: number) => {
  try {
    await portApi.setInterface(catalogId, infoId)
    message.success('接口设置成功')
    // 刷新列表数据
    await getList()
  } catch (error) {
    message.error('接口设置失败')
  }
}

/** 打开设置弹窗 */
const openSettingsDialog = (row: any) => {
  catalogIdValue.value = row.catalogId
  infoId.value = row.infoId || undefined
  originalInfoId.value = row.infoId || undefined // 保存原始infoId
  settingsDialogVisible.value = true
  selectedRow.value = null
  // 初始化弹窗查询参数
  Object.assign(dialogQueryParams, {
    pageNo: 1,
    pageSize: 10,
    serviceUrl: undefined,
    interfacePath: undefined,
    interfaceType: undefined,
    interfaceMethod: undefined,
    interfaceCode: undefined,
    contentType: undefined,
    createTime: [],
    remark: undefined,
    interfaceName: undefined,
    id: undefined
  })
  getDialogList()
}

/** 处理弹窗关闭 */
const handleDialogClose = () => {
  // 恢复原始infoId状态
  if (originalInfoId.value !== undefined) {
    infoId.value = originalInfoId.value
  }
  settingsDialogVisible.value = false
  selectedRow.value = null
}

/** 处理当前行变化 - 真正的单选逻辑 */
const handleCurrentChange = (currentRow: any) => {
  if (currentRow) {
    selectedRow.value = currentRow
    infoIdValue.value = currentRow.id
  } else {
    selectedRow.value = null
    infoIdValue.value = undefined
  }
}

/** 提交选中的数据 */
const handleSubmit = async () => {
  try {
    // 这里可以处理选中的接口数据
    await setInterface(catalogIdValue.value, infoIdValue.value)
    settingsDialogVisible.value = false

    // 可以根据需要刷新主页面数据
    await getList()
  } catch (error) {
    message.error('设置失败')
  }
}

/** 更换接口设置 */
const handleChangeInterface = () => {
  // 清除infoId
  infoId.value = undefined
  // 清除选中状态
  if (dialogTableRef.value) {
    dialogTableRef.value.setCurrentRow()
  }
  selectedRow.value = null
  // 重新查询列表
  getDialogList()
  message.success('已清除当前选中状态，请重新选择接口')
}

/** 显示JSON对话框 */
const showJsonDialog = (title: string, content: string) => {
  jsonDialogTitle.value = title
  jsonContent.value = content ? formatJsonContent(content) : '暂无数据'
  jsonDialogVisible.value = true
}

/** 格式化JSON内容 */
const formatJsonContent = (jsonStr: string) => {
  try {
    if (!jsonStr) return '暂无数据'
    const jsonObj = JSON.parse(jsonStr)
    return JSON.stringify(jsonObj, null, 2)
  } catch (e) {
    return jsonStr // 如果不是标准JSON，直接返回原字符串
  }
}

/** 复制JSON */
const copyJson = async () => {
  try {
    await navigator.clipboard.writeText(jsonContent.value)
    message.success('复制成功')
  } catch (err) {
    message.error('复制失败')
  }
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>

<style scoped>
.settings-content {
  max-height: 60vh;
  overflow-y: auto;
}

/* 优化选中行样式 */
:deep(.el-table__body tr.current-row > td.el-table__cell) {
  background-color: #e6f7ff !important;
}

/* 优化表单样式 */
.el-form {
  padding: 20px 0;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
